package com.rslai.base.tool.servertest.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.apache.commons.lang.StringUtils;

public class IpUtil {
    private static final char COLON = ':';

    public static String getLocalNetworkAddress() {
        try {
            Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                String address = getAddressForNic(ni);
                if (StringUtils.isNotBlank(address)) return address;
            }
            return "";
        } catch (Exception e) {
        }
        return "";
    }

    private static String getAddressForNic(NetworkInterface nic) {
        Enumeration addresses = nic.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress ip = (InetAddress) addresses.nextElement();
            if ((!ip.isLoopbackAddress()) && (!isIPv6(ip))) {
                return ip.getHostAddress();
            }
        }
        return "";
    }

    private static boolean isIPv6(InetAddress ip) {
        return ip.getHostAddress().indexOf(':') != -1;
    }
}
